// pages/project2/calculate/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wagesValue: '26500',
    socialValue: '0',
    monthDetailList: []
  },

  changeInput(e) {
    switch (e.target.dataset.type) {
      case 'wages':
        this.setData({
          wagesValue: e.detail.value,
        })
        break;
      case 'social':
        this.setData({
          socialValue: e.detail.value,
        })
        break;
      default:
        break;
    }

  },

  submit() {
    if (this.data.wagesValue.length == 0 || this.data.socialValue.length == 0) {
      wx.showToast({
        title: '请先填写月工资和社保扣除',
        icon: "none"
      })
    } else {
      this.calculate()
    }
  },

  calculate() {
    for (let index = 1; index <= 12; index++) {
      const montDetail = {
        month: index + '月',
        wages: this.data.wagesValue,
        yearRevenue: this.calculateRevenue(this.data.wagesValue, this.data.socialValue, index),
        monthRevenue: this.calculateRevenue(this.data.wagesValue, this.data.socialValue, index) - this.calculateRevenue(this.data.wagesValue, this.data.socialValue, index - 1)
      }

      this.setData({
        monthDetailList: [...this.data.monthDetailList, montDetail]
      })
    }
  },

  calculateRevenue(wages, social, month) {
    const taxFreeAmount = 5000; // 年度免税额度
    // 年度税率分段
    const incomeSegments = [
      { min: 0, max: 36000, rate: 0.03, infull: 0 },
      { min: 36000, max: 144000, rate: 0.10, infull: 1080 },
      { min: 144000, max: 300000, rate: 0.20, infull: 11880 },
      { min: 300000, max: 420000, rate: 0.25, infull: 43080 },
      { min: 420000, max: 660000, rate: 0.30, infull: 73080 },
      { min: 660000, max: 960000, rate: 0.35, infull: 145080 },
      { min: 960000, max: Infinity, rate: 0.45, infull: 250080 }
    ];
    let taxableIncome = (wages - taxFreeAmount - social) * month
    let totalTax = 0

    for (const segment of incomeSegments) {
      if (taxableIncome > segment.min && taxableIncome < segment.max) {
        totalTax = segment.infull + (taxableIncome - segment.min) * segment.rate
      }
    }

    return totalTax
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.submit()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})